class Solution {
public:
    string reverseWords(string s) {
        while(*s.begin()==' '){
            s.erase(s.begin());
        }
        reverse(s.begin(),s.end());
        auto begin=s.begin();
        //将单词反转
        int flag=0;
        while(begin!=s.end()){
            auto end=begin;
            while(*end!=' '&&end!=s.end()){
                end++;
            }
            reverse(begin,end);
            
            auto count=end;
            while(*end==' '){
                flag++;
                end++;
            }
            
            if(flag>=1){
                s.erase(count,count+flag-1);
                flag=0;
            }

            end=count;
            if(end!=s.end()){
                end++;
            }

            begin=end;
        }
        while(*s.begin()==' '){
            s.erase(s.begin());
        }
        return s;
    }
};